"""
主题相关的Pydantic schema
"""
from pydantic import BaseModel, Field, validator
from typing import List, Optional
from datetime import datetime


class ThemeBase(BaseModel):
    """主题基础模型"""
    name: str = Field(..., max_length=255, description="主题名称")
    description: Optional[str] = Field(None, description="主题描述")
    keywords: Optional[List[str]] = Field(default_factory=list, description="关键词列表")
    style: Optional[str] = Field(None, max_length=100, description="写作风格")
    target_audience: Optional[str] = Field(None, max_length=100, description="目标受众")
    content_length: int = Field(1500, ge=100, le=10000, description="内容长度要求")
    is_active: bool = Field(True, description="是否启用")

    @validator('keywords')
    def validate_keywords(cls, v):
        if v and len(v) > 10:
            raise ValueError('关键词数量不能超过10个')
        return v

    @validator('name')
    def validate_name(cls, v):
        if not v or not v.strip():
            raise ValueError('主题名称不能为空')
        return v.strip()


class ThemeCreate(ThemeBase):
    """创建主题模型"""
    pass


class ThemeUpdate(BaseModel):
    """更新主题模型"""
    name: Optional[str] = Field(None, max_length=255, description="主题名称")
    description: Optional[str] = Field(None, description="主题描述")
    keywords: Optional[List[str]] = Field(None, description="关键词列表")
    style: Optional[str] = Field(None, max_length=100, description="写作风格")
    target_audience: Optional[str] = Field(None, max_length=100, description="目标受众")
    content_length: Optional[int] = Field(None, ge=100, le=10000, description="内容长度要求")
    is_active: Optional[bool] = Field(None, description="是否启用")

    @validator('keywords')
    def validate_keywords(cls, v):
        if v and len(v) > 10:
            raise ValueError('关键词数量不能超过10个')
        return v

    @validator('name')
    def validate_name(cls, v):
        if v is not None and (not v or not v.strip()):
            raise ValueError('主题名称不能为空')
        return v.strip() if v else v


class ThemeResponse(ThemeBase):
    """主题响应模型"""
    id: str = Field(..., description="主题ID")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")

    class Config:
        from_attributes = True
        json_encoders = {
            datetime: lambda v: v.isoformat()
        }


class ThemeListResponse(BaseModel):
    """主题列表响应模型"""
    items: List[ThemeResponse]
    total: int
    page: int
    page_size: int
    has_next: bool